package com.zhou.mvc;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class DispatcherServlet extends HttpServlet {
    //初始化方法 利用反射机制事先把类以及方法进行预处理
    @Override
    public void init(ServletConfig config) throws ServletException {
        //读取配置文件路径
        String path = config.getInitParameter("contentConfigLocation");
        //配置文件内容转换为输入流
        InputStream is = DispatcherServlet.class.getClassLoader().getResourceAsStream(path);
        //把配置文件的输入流传入此处理器 利用反射机制事先把配置文件中指定的类以及方法进行预处理
        HandleMapping.load(is);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取用户请求的uri
        String uri = req.getRequestURI();
        HandleMapping.MVCMapping mapping = HandleMapping.get(uri);
        if(mapping==null){
            resp.sendError(404,"自定义MVC:映射地址不存在"+uri);
            return;
        }
        Object obj = mapping.getObj();
        Method method = mapping.getMethod();
        String result = null;
        try {
            //利用反射直接调用此方法并且获得此方法的返回值
            result = (String) method.invoke(obj, req, resp);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        switch (mapping.getType()){
            case TEXT:
                //如果是纯文本就利用打印流直接写回前端页面
                resp.getWriter().write(result);
                break;
            case VIEW:
                //如果是视图 就直接进行重定向
                resp.sendRedirect(result);
                break;
        }
    }
}
